package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/net/context"
	"net/http"
	"tiktok-platform/api/request"
	"tiktok-platform/consts"
	"tiktok-platform/global"
	"tiktok-platform/internal/dao"
	"tiktok-platform/internal/model"
	"tiktok-platform/pkg"
	"time"
)

func RegisterUser(c *gin.Context) {
	var req request.RegisterUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		return
	}

	if req.Mobile == "" || req.Password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	err := dao.GetOnrBNyFile(&model.User{Mobile: req.Mobile}, &user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	user = model.User{
		Mobile:   req.Mobile,
		Password: pkg.Md5(req.Password),
	}

	err = dao.AddFile(&user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "注册成功",
		"data": nil,
	})

}

func LoginUser(c *gin.Context) {
	var req request.LoginUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		return
	}

	if req.Mobile == "" || req.Password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	err := dao.GetOnrBNyFile(&model.User{Mobile: req.Mobile}, &user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "登陆失败",
			"data": nil,
		})
		return
	}

	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "登陆失败:账号或密码错误",
			"data": nil,
		})
		return
	}

	if user.Password != pkg.Md5(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "登陆失败:账号或密码错误",
			"data": nil,
		})
		return
	}

	token := pkg.CreateJwtToken(user.Id, 24*time.Hour, consts.JWT_KEY)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "登陆成功",
		"data": token,
	})
	global.RDB.Set(context.Background(), fmt.Sprintf("token:%d", token), user.Id, 24*time.Hour)
}

func ListUser(c *gin.Context) {
	
}

func FindUser(c *gin.Context) {
	
}